module("kong.plugins.rbactest.cache", package.seeall)

local redis = require "resty.redis"

local rbac_cache_prefix = "rbac_"

--redis的配置信息
local redis_conf = {
    timeout = 3000,
    host = "XXXX.tech",
    port = 5705,
    passwd = "XXXXX",
    db = 3
}
--根据token获取租户信息
function get_authorization_user_info(token, red)
  local res, err = red:get(token.."_tenant")
  if not res then
      kong.log.err("failed to run get_authorization_code:" ..
                       err)
  end
  return res
end

--根据权限key找到对应的角色
function get_roles_by_permission(permission_key, red)
    local res, err = red:smembers(rbac_cache_prefix..permission_key)
    if not res then
        kong.log.err(
            "failed to run get_permission_roles_from_cache, role_id:" ..
                permission_key, err)
    end
    return res
end

--根据用户查找对应的角色
function get_roles_by_user(user_id, red)
  local user_key = rbac_cache_prefix..user_id
    local res, err = red:smembers(user_key)
    if not res then
        kong.log.err("failed to run get_roles_by_user_from_cache, role_id:" ..
                         user_id, err)
    end
    return res
end

-- connect to redis
--用到的地方使用  local red = cache.connect_to_redis()
--使用完之后 调用 cache.close_redis(red) 关闭连接
function connect_to_redis()
    local red = redis:new()
    red:set_timeout(redis_conf.timeout)

    local ok, err = red:connect(redis_conf.host, redis_conf.port)
    if err then return nil, err end

    if redis_conf.passwd and redis_conf.passwd ~= "" then
        local ok, err = red:auth(redis_conf.passwd)
        if err then return nil, err end
    end
    if redis_conf.db then
        red:select(redis_conf.db)
    end
    return red
end

function close_redis(red)
  if red then
    red:close()
  end
end
